<template>
  <div class="project-management-container">
    <!-- 筛选条件区域 -->
    <div class="filter-container">
      <el-form :model="filterParams" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="项目名称">
              <el-input
                v-model="filterParams.projectName"
                placeholder="请输入项目名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目产业类别">
              <el-select
                v-model="filterParams.industryCategory"
                placeholder="请选择产业类别"
                clearable
              >
                <el-option
                  v-for="item in industryOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="投资方">
              <el-input
                v-model="filterParams.investor"
                placeholder="请输入投资方"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
  <el-form-item label="项目类型">
    <el-select
      v-model="filterParams.projectType"
      placeholder="请选择项目类型"
      clearable
    >
      <el-option
        v-for="item in projectTypeOptions"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
  </el-form-item>
</el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" @click="handleQuery">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="operation-container">
      <el-button type="primary" @click="handleExport" :title="selectedProjects.length > 0 ? '导出选中项目' : '导出全部项目'">
       <el-icon><Download /></el-icon>
       导出Excel
       <span v-if="selectedProjects.length > 0">({{ selectedProjects.length }}项)</span>
      </el-button>
      <el-button type="success" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增项目
      </el-button>
    </div>

    <!-- 项目表格区域 -->
    <div class="table-container">
       <!-- 标题和分割线 -->
      <div class="header-section">
        <h1 class="contract-title">竣工验收项目</h1>
        <div class="divider"></div>
      </div>
      <el-table
        :data="paginatedProjects"
        border
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="项目名称" width="200">
         <template #default="{ row }">
          <router-link 
           :to="{
             name: 'SignedProjectDetail',
             params: { id: row.id },
             query: { type: 'construction',projectData: JSON.stringify(row) }
           }"
          class="project-link"
          >
          {{ row.projectName }}
         </router-link>
         </template>
        </el-table-column>
        <el-table-column prop="projectCode" label="项目编号"  width="150"/>
        <el-table-column prop="investor" label="投资方" width="150" />
        <el-table-column prop="contactPerson" label="联系人" width="120" />
        <el-table-column prop="industryCategory" label="项目产业类别" width="150">
          <template #default="{ row }">
            <el-tag :type="getIndustryTagType(row.industryCategory)">
              {{ row.industryCategory }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="parkName" label="所属园区" width="150" />
      <!-- 审核步骤部分 -->
<el-table-column label="审核进度" width="750">
  <template #default="{ row }">
    <!-- 独立选址项目步骤 -->
    <el-steps 
      v-if="row.type === 'independent'"
      align-center 
      :active="getActiveStep(row)" 
      finish-status="success"
    >
      <el-step 
        title="组织竣工验收"
        description="建设单位"
        :icon="getStepIcon(row, 1)"
        :status="getStepStatus(row, 1)"
      />
      <el-step 
        title="报请部门联合验收"
        description="建设发展局"
        :icon="getStepIcon(row, 2)"
        :status="getStepStatus(row, 2)"
      />
      <el-step 
        title="竣工验收备案"
        description="行政审批局"
        :icon="getStepIcon(row, 3)"
        :status="getStepStatus(row, 3)"
      />
      <el-step 
        title="不动产登记审批"
        description="县自然资源和规划局"
        :icon="getStepIcon(row, 4)"
        :status="getStepStatus(row, 4)"
      />
    </el-steps>
    
    <!-- 租赁厂房项目步骤 -->
    <el-steps 
      v-else
      align-center 
      :active="getActiveStep(row)" 
      finish-status="success"
    >
      <el-step 
        title="上传并联事项文件"
        description="县生态环境局"
        :icon="getStepIcon(row, 1)"
        :status="getStepStatus(row, 1)"
      />
      <el-step 
        title="审批并联事项文件"
        description="行政审批局"
        :icon="getStepIcon(row, 2)"
        :status="getStepStatus(row, 2)"
      />
    </el-steps>
  </template>
</el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
  <template #default="{ row }">
    <el-button
      type="info"
      size="small"
      @click="handleReview2(row)"
      style="margin-bottom: 5px;"
    >
      审核
    </el-button>
  



  </template>
</el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑项目对话框 -->
    <ProjectDialog
      v-model="dialogVisible"
      :dialog-type="dialogType"
      :current-project="currentProject"
      @submit="handleProjectSubmit"
    />

  


  </div>
</template>

<script setup>
import { ref, onMounted,computed,watch } from 'vue'
import { Download, Plus,Check,Clock } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as XLSX from 'xlsx'
import ProjectDialog from './component/ProjectDialog.vue'
import { useProjectStore } from '@/stores/project'
import { useRouter,useRoute } from 'vue-router'
import axios from 'axios'
// API基础URL（从环境变量获取，自动适配环境）
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;
const router = useRouter()
const route = useRoute()
const projectStore = useProjectStore()
// 存储各项目的审核记录映射
const auditRecordsMap = ref({})
// 存储各项目的当前步骤 { projectId: step }
const activeSteps = ref({})
const projects = ref([])
// 使用计算属性获取过滤后的项目列表
const filteredProjects = computed(() => {
  return projects.value.filter(item => item.state === 'completion')
})
// 新增：获取项目列表的方法
const fetchProjectList = async () => {
  loading.value = true
  try {
    console.log('发送请求，参数:', filterParams.value)
    const response = await axios.get(`${API_BASE_URL}/api/projects`, {
      params: {
        ...filterParams.value
      }
    })
    console.log('收到响应:', response.data)
    projects.value = response.data
    console.log('项目数据已更新，数量:', projects.value.length)
    
    // 获取项目列表后，立即获取审核记录
    await fetchAllAuditRecords()
    
  } catch (error) {
    console.error('获取项目列表失败:', error)
    if (error.response) {
      console.error('响应状态:', error.response.status)
      console.error('响应数据:', error.response.data)
    }
    ElMessage.error('获取项目列表失败')
  } finally {
    loading.value = false
  }
}

// 一次性获取所有项目的审核记录
const fetchAllAuditRecords = async () => {
  try {
    // 并发获取所有项目的审核记录
    const auditRequests = projects.value.map(project => 
      axios.get(`${API_BASE_URL}/api/projects/${project.id}/audit-records`)
        .then(response => ({
          projectId: project.id,
          records: response.data
        }))
        .catch(error => ({
          projectId: project.id,
          records: []
        }))
    )
    
    const auditResults = await Promise.all(auditRequests)
    
    // 构建审核记录映射
    auditResults.forEach(({ projectId, records }) => {
      if (records && records.length > 0) {
        // 找到最大ID的记录
        const maxIdRecord = records.reduce((prev, current) => 
          prev.id > current.id ? prev : current
        )
        
        // 计算当前步骤
        const activeStep = calculateActiveStep(maxIdRecord)
        activeSteps.value[projectId] = activeStep
        
        // 缓存最大记录用于状态计算
        auditRecordsMap.value[projectId] = [maxIdRecord]
      } else {
        activeSteps.value[projectId] = 1
        auditRecordsMap.value[projectId] = []
      }
    })
    
  } catch (error) {
    console.error('获取审核记录失败:', error)
  }
}

// 简化的步骤计算函数
const calculateActiveStep = (maxIdRecord) => {
  if (!maxIdRecord) return 1
  
  if (maxIdRecord.status === '已通过' || maxIdRecord.status === '已提交') {
    return maxIdRecord.step + 1
  } else if (maxIdRecord.status === '已驳回') {
    return maxIdRecord.step === 5 ? maxIdRecord.step : Math.max(maxIdRecord.step - 1, 1)
  } else {
    return maxIdRecord.step
  }
}

// 获取活跃步骤
const getActiveStep = (row) => {
  return activeSteps.value[row.id] || 1
}

// 简化的步骤状态计算
const getStepStatus = (row, stepIndex) => {
  const records = auditRecordsMap.value[row.id] || []
  const maxIdRecord = records[0] // 这里只存了最大ID记录
  
  if (!maxIdRecord) {
    return stepIndex === 1 ? 'process' : 'wait'
  }
  
  // 简化的状态判断逻辑
  if (stepIndex < maxIdRecord.step) return 'success'
  if (stepIndex === maxIdRecord.step) {
    return maxIdRecord.status === '已驳回' ? 'error' : 'success'
  }
  if (stepIndex === maxIdRecord.step + 1) {
    return (maxIdRecord.status === '已通过' || maxIdRecord.status === '已提交') ? 'process' : 'wait'
  }
  return 'wait'
}

// 获取步骤图标
const getStepIcon = (row, stepIndex) => {
  const status = getStepStatus(row, stepIndex)
  if (status === 'process') {
    return Clock
  }
  return undefined
}

// 处理审核操作
const handleReview2 = (row) => {
  const activeStep = getActiveStep(row)
  let department = ''
  
  if (row.type === 'independent') {
    // 独立选址项目的部门映射
    const departments = [
      '建设单位',
      '建设发展局',
      '行政审批局',
      '县自然资源和规划局'
    ]
    department = departments[Math.min(activeStep - 1, departments.length - 1)]
  } else {
    // 租赁厂房项目只有一个部门
    department = '县生态环境局'
  }
  
  router.push({
    path: '/fileapproval',
    query: {
      projectId: row.id,
      department: department,
      currentStep: activeStep
    }
  })
}

// 筛选参数
const filterParams = ref({
  projectName: '',
  industryCategory: '',
  investor: '',
  projectType: '' // 新增项目类型筛选
})

// 产业类别选项
const industryOptions = ref([
  { value: '制造业', label: '制造业' },
  { value: '信息技术', label: '信息技术' },
  { value: '金融业', label: '金融业' },
  { value: '教育培训', label: '教育培训' },
  { value: '医疗健康', label: '医疗健康' },
  { value: '零售业', label: '零售业' },
  { value: '物流运输', label: '物流运输' },
  { value: '建筑工程', label: '建筑工程' },
  { value: '餐饮服务', label: '餐饮服务' },
  { value: '文化娱乐', label: '文化娱乐' },
  { value: '房地产', label: '房地产' },
  { value: '能源环保', label: '能源环保' },
  { value: '农业', label: '农业' },
  { value: '旅游酒店', label: '旅游酒店' },
  { value: '媒体广告', label: '媒体广告' },
  { value: '咨询服务', label: '咨询服务' },
  { value: '其他行业', label: '其他行业' }
])
// 添加项目类型选项
const projectTypeOptions = ref([
  { value: 'independent', label: '独立选址' },
  { value: 'rental', label: '租赁厂房' }
])



// 分页后的项目列表
const paginatedProjects = computed(() => {
  const start = (pagination.value.currentPage - 1) * pagination.value.pageSize
  const end = start + pagination.value.pageSize
  return filteredProjects.value.slice(start, end)
})

// 分页参数
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: computed(() => filteredProjects.value.length)
})

// 加载状态
const loading = ref(false)

// 对话框控制
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' or 'edit'
const currentProject = ref({})


// 查询项目
const handleQuery = () => {
  pagination.value.currentPage = 1
  fetchProjectList()
}

// 重置筛选条件
const handleReset = () => {
  filterParams.value = {
    projectName: '',
    industryCategory: '',
    investor: ''
  }
  handleQuery()
}

// 添加选中项目的ref
const selectedProjects = ref([])

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedProjects.value = selection
}


// 导出Excel方法
const handleExport = () => {
  // 如果有选中项目，则导出选中项目，否则导出全部
  const exportData = selectedProjects.value.length > 0 
    ? selectedProjects.value 
    : filteredProjects.value
  
  if (exportData.length === 0) {
    ElMessage.warning('没有可导出的项目数据')
    return
  }

  const worksheet = XLSX.utils.json_to_sheet(exportData)
  const workbook = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(workbook, worksheet, '项目信息')
  
  const fileName = selectedProjects.value.length > 0
    ? `选中项目_${new Date().toLocaleDateString()}.xlsx`
    : `全部项目_${new Date().toLocaleDateString()}.xlsx`
  
  XLSX.writeFile(workbook, fileName)
}


// 新增项目
const handleAdd = () => {
  dialogType.value = 'add'
  currentProject.value = {
    projectName: '',
    projectCode: '',
    investor: '',
    contactPerson: '',
    industryCategory: '',
    parkName: '',
    description: '',
    type: 'independent',
    status:'审核中',
    state: 'landApproval',
    auditStatus: '审核中' 
  }
  dialogVisible.value = true
}

const handleProjectSubmit = (newProject) => {
  const projectToAdd = {
    ...newProject,
    state: 'completion',
    signDate: new Date().toISOString().split('T')[0]
  }
  
  if (dialogType.value === 'add') {
    // 调用store方法添加项目
    projectStore.addProject(projectToAdd)
    // 重置分页到第一页
    pagination.value.currentPage = 1
  } else {
    // 如果是编辑，也需要更新状态
    projectStore.updateProject(projectToAdd)
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.value.pageSize = val
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.value.currentPage = val
}

// 获取产业类别标签类型
const getIndustryTagType = (category) => {
  const map = {
    '智能制造': '',
    '电子信息': 'success',
    '生物医药': 'warning',
    '新能源': 'danger',
    '新材料': 'info'
  }
  return map[category] || ''
}

onMounted(()=>{
  fetchProjectList()
})

</script>

<style scoped>
.project-management-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
  background-color: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
}

.operation-container {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.table-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.filter-container {
  margin-bottom: 24px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}
.header-section {
  margin-bottom: 30px;
}

.contract-title {
  font-size: 20px;
  color: #29c64e;
  margin-bottom: 10px;
  text-align: left;
}

.divider {
  height: 1px;
  background-color: #e0e0e0;
  width: 100%;
}

/* 时钟图标样式 */
:deep(.el-step__icon.is-process) {
  background-color: #e6a23c;
  color: white;
}
/* 步骤条样式 */
:deep(.el-step__head.is-process) {
  color: #e6a23c; /* 黄色 */
  border-color: #e6a23c;
}

:deep(.el-step__title.is-process) {
  color: #e6a23c; /* 黄色 */
  font-weight: bold;
}

/* 完成状态保持绿色 */
:deep(.el-step__head.is-success) {
  color: #67C23A;
  border-color: #67C23A;
}

/* 错误状态保持红色 */
:deep(.el-step__head.is-error) {
  color: #F56C6C;
  border-color: #F56C6C;
}

/* 等待状态保持灰色 */
:deep(.el-step__head.is-wait) {
  color: #C0C4CC;
  border-color: #C0C4CC;
}

/* 新增：步骤描述跟随状态变色 */
:deep(.el-step__description.is-process) {
  color: #e6a23c; /* 黄色 */
  font-weight: bold;
}

:deep(.el-step__description.is-success) {
  color: #67C23A; /* 绿色 */
}

:deep(.el-step__description.is-error) {
  color: #F56C6C; /* 红色 */
}

:deep(.el-step__description.is-wait) {
  color: #C0C4CC; /* 灰色 */
}
</style>